import { useCourseInfo, useEditCourseInfo } from "@/services/course";
import type { IOrderTime, IWeekCourse } from "@/utils/types";
import { useMemo } from "react";
import { DAYS, isWorkDay, type IDay } from "./constants";

export const useOrderTime = ( id:string, currentDay:IDay ) => {
//   const [currentDay, setCurrentDay] = useState<IDay>(DAYS[0]);
  //   const [reducibleTime, setReducibleTime] = useState<IWeekCourse>();
  const { data, refetch, loading } = useCourseInfo(id);
  const [edit, editLoading] = useEditCourseInfo();
  //   const reducibleTime = data?.reducibleTime || [];
  //   console.log("data?.reducibleTime", data?.reducibleTime);

  const orderTime = useMemo(
    () =>
      ((data?.reducibleTime || []).find((item) => item.week === currentDay.key)
        ?.orderTime || []) as IOrderTime[],
    [data, currentDay]
  );
  //   console.log("orderTime", orderTime);
//   const onTabChangeHandler = (key: string) => {
//     const current = DAYS.find((item) => item.key === key) as IDay;
//     setCurrentDay(current);
//   };

  const onSaveHandler = (ot: IOrderTime[]) => {
    const rt = [...(data?.reducibleTime || [])];
    const index = rt.findIndex((item) => item.week === currentDay.key);
    if (index > -1) {
      rt[index] = {
        week: currentDay.key,
        orderTime: ot,
      };
    } else {
      rt.push({
        week: currentDay.key,
        orderTime: ot,
      });
    }
    edit(id, { reducibleTime: rt }, () => refetch());
  };
  const onDeleteHandler = (key: number) => {
    const newData = orderTime.filter((item) => item.key !== key);
    onSaveHandler(newData);
  };
  const allWorkDaySyncHandler = () => {
    const rt: IWeekCourse[] = [];
    DAYS.forEach((item) => {
      if (isWorkDay(item.key)) {
        rt.push({
          week: item.key,
          orderTime,
        });
      }
    });
    edit(id, { reducibleTime: rt }, () => refetch());
  };
  const allWeekSyncHandler = () => {
    const rt: IWeekCourse[] = [];
    DAYS.forEach((item) => {
      rt.push({
        week: item.key,
        orderTime,
      });
    });
    edit(id, { reducibleTime: rt }, () => refetch());
  };
  return {
    currentDay,
    orderTime,
    loading:loading || editLoading,
    // editLoading,
    // onTabChangeHandler,
    onSaveHandler,
    onDeleteHandler,
    allWorkDaySyncHandler,
    allWeekSyncHandler,
  };
};
